import express from 'express'
import { createProxyMiddleware } from './fix/proxyMiddleware'
import { join } from 'path'
import history from 'connect-history-api-fallback'

export class AppServer {
  app = express()
  _listenPromise
  _server

  constructor() {
    if (__DEV__) {
      const DEV_URL = process.env.DEV_URL
      if (DEV_URL) {
        this.app.use('/', createProxyMiddleware({ target: DEV_URL, changeOrigin: true }))
      }
    }

    this.app.use(history()).use(express.static(join(__dirname, __RENDERER__)))

    process.on('exit', () => this.close())
  }

  listen(port = 0, hostname = 'localhost') {
    return (
      this._listenPromise ??
      (this._listenPromise = new Promise((resolve, reject) => {
        const server = (this._server = this.app.listen(port, hostname, () => {
          const { address, port } = server.address()

          const url = `http://${address}:${port}`
          resolve(url)
          console.info(`Application is running on ${url}`)
        }))
      }))
    )
  }

  close() {
    this._server?.close()
    this._server = this._listenPromise = undefined
  }
}

export const appServer = new AppServer()
appServer.listen()
